/**
 * Created with JetBrains WebStorm.
 * User: Fred_974
 * Date: 14/06/13
 * Time: 11:16
 * To change this template use File | Settings | File Templates.
 */
var connector = require('./connector');
var connection = connector.connection();
// We need our model
var UserPlantation = require("./UserPlantation");


var persistUserPlantation = function(userPlantation, callback){

    var post  = {plantation : userPlantation.plantation,
        tile: userPlantation.tile, maturity : userPlantation.maturity,real_maturity : userPlantation.real_maturity,
            real_health : userPlantation.real_health, health : userPlantation.health}

    if(userPlantation.id == null){

        connection.query('INSERT INTO user_plantation SET ?', post, function(err, result, fields){

            if (err) throw err; // if there is an error we throw it
            userPlantation.id = result.insertId;
            callback(userPlantation); // Callback basicaly it's the end of the controleur
        });

    }else{
        connection.query('update user_plantation SET ? where id = ?',[post,userPlantation.id], function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            callback(rows[0]); // Callback basicaly it's the end of the controleur
        });

    }


};

var findAll = function(callback){
    connection.query('select * from user_plantation', function(err, rows, fields){

        if (err) throw err; // if there is an error we throw it

        var ups = new Array();

        for(var i = 0; i < rows.length; i++){
            var up = new UserPlantation();
            up.init(rows[i]);
            ups.push(up);
        }

        callback(ups); // Callback basicaly it's the end of the controleur
    });
}


var deletePlantation = function(id, callback){

    if(id != null){

        connection.query('delete from user_plantation where id ='+id, function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            if (callback != null)
                callback(rows);
        });
    }
}

exports.persistUserPlantation = persistUserPlantation;
exports.deletePlantation = deletePlantation;
exports.findAll = findAll;
